package com.mall.member.service.impl;

import ch.qos.logback.core.pattern.color.BoldCyanCompositeConverter;
import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mall.common.exception.HttpStatusCode;
import com.mall.common.service.impl.CrudServiceImpl;
import com.mall.common.utils.ConvertUtils;
import com.mall.common.utils.DateUtils;
import com.mall.common.utils.Result;
import com.mall.common.vo.UserInfoVo;
import com.mall.member.dao.MemberDao;
import com.mall.member.dto.MemberDTO;
import com.mall.member.entity.MemberEntity;
import com.mall.member.service.MemberLevelService;
import com.mall.member.service.MemberService;
import com.mall.member.vo.LoginVo;
import com.mall.member.vo.MemberRegistryVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 会员
 *
 * @author xjc xjc@163.com
 * @since 1.0.0 2022-07-17
 */
@Service
@Slf4j
public class MemberServiceImpl extends CrudServiceImpl<MemberDao, MemberEntity, MemberDTO> implements MemberService {

    @Resource
    private MemberLevelService memberLevelService;

    @Override
    public QueryWrapper<MemberEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<MemberEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public Result registry(MemberRegistryVo memberRegistryVo) {
        // 检查userName 唯一
        if (checkUserNameUnique(memberRegistryVo.getUserName())) {
            return new Result().error(HttpStatusCode.USER_NAME_EXIST_EXCEPTION.getCode(),HttpStatusCode.USER_NAME_EXIST_EXCEPTION.getMsg());
        }
        // 检查phone 唯一
        if (checkPhoneUnique(memberRegistryVo.getPhone())) {
            return new Result().error(HttpStatusCode.PHONE_EXIST_EXCEPTION.getCode(),HttpStatusCode.PHONE_EXIST_EXCEPTION.getMsg());
        }
        MemberEntity member = new MemberEntity();
        // 随机盐
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(memberRegistryVo.getPassword());
        member.setPassword(encode);
        member.setUsername(memberRegistryVo.getUserName());
        try {
            member.setLevelId(memberLevelService.selectByDefaultId().getId());
        } catch (Exception e) {
            log.info("获取默认会员等级失败");
        }
        member.setCreateTime(new DateTime());
        baseDao.insert(member);
        return new Result().ok("注册成功");
    }

    @Override
    public Result login_pwd(LoginVo loginVo) {
        QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", loginVo.getLoginAccount()).or().eq("mobile",loginVo.getLoginAccount());
        try {
            MemberEntity member = baseDao.selectOne(queryWrapper);
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            boolean matches = encoder.matches(loginVo.getPassword(), member.getPassword());
            if (!matches)
                throw new RuntimeException("密码不匹配");
            return new Result().ok(ConvertUtils.sourceToTarget(member, UserInfoVo.class));
        } catch (RuntimeException e) {
            return new Result().error(HttpStatusCode.PASSWORD_EXCEPTION.getCode(),HttpStatusCode.PASSWORD_EXCEPTION.getMsg());
        }
    }

    public boolean checkUserNameUnique(String userName) {
        return baseDao.selectCount(new QueryWrapper<MemberEntity>().eq("username",userName))>0;
    }
    public boolean checkPhoneUnique(String phone) {
        return baseDao.selectCount(new QueryWrapper<MemberEntity>().eq("mobile",phone))>0;
    }
}